package com.springsecurity.service;

import com.springsecurity.pojo.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    SysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //自定义逻辑,验证用户是否存在
       /* if (!"admin".equals(username)) {
            throw new UsernameNotFoundException("用户名不存在！");
        }*/

        SysUser loginUser = sysUserService.login(username);
        if (null==loginUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        List<GrantedAuthority> auths =AuthorityUtils.commaSeparatedStringToAuthorityList
                ("L01,L05,ROLE_admin"); //权限列表,ROLE_* 角色列表

        //方式1: 静态数据
       /* return new User(username
                        ,passwordEncoder.encode("123456")
                        //角色: admin ,normal
                        , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal"));*/

        //方式2: 动态数据
        return new User(loginUser.getUsrName()
                ,passwordEncoder.encode(loginUser.getUsrPassword())
                //角色: admin ,normal
                ,auths);
    }


}
